<?php
class User extends Admin_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('user_model','user');
	}
	
	function index()
	{
		$where = '1 = 1';
		if(!empty($_GET['firstname']))
		{
			$where .= ' and users.firstname like \'%'.$_GET['firstname'].'%\'';
		}
		if(!empty($_GET['lastname']))
		{
			$where .= ' and users.lastname like \'%'.$_GET['lastname'].'%\'';
		}
		if(!empty($_GET['level_id']))
		{
			$where .= ' and users.level_id = '.$_GET['level_id'];
		}
		if(!empty($_GET['agency_id']))
		{
			$where .= ' and users.agency_id = '.$_GET['agency_id'];
		}
		$this->user->where($where);
		$data['result'] = $this->user->get();
		$data['pagination'] = $this->user->pagination();
		$this->template->build('user_index',$data);
	}
	
	function form($id = NULL)
	{
		$data['rs'] = $this->user->get_row($id);
		$this->template->append_metadata(js_validate());
		$this->template->build('user_form',$data);
	}
	
	function save()
	{
		if($_POST)
		{
			if(empty($_POST['id']))
			{
				add_log('เพิ่มผู้ใช้งาน "'.$_POST['username'].'"');
			}
			else
			{
				add_log('แก้ไขผู้ใช้งาน "'.$_POST['username'].'"');
			}
			
			if(!isset($_POST['FUND1']))$_POST['FUND1']=0;
			if(!isset($_POST['FUND2']))$_POST['FUND2']=0;
			if(!isset($_POST['FUND3']))$_POST['FUND3']=0;
			if(!empty($_POST['password']))
			{
				$_POST['password'] = md5($_POST['password']);
			}
			else
			{
				unset($_POST['password']);
			}
			$this->user->save($_POST);
			set_notify('success', lang('save_data_complete'));
		}
		redirect('user');
	}
	
	function delete($id)
	{
		$rs = $this->user->get_row($id);
		add_log('ลบผู้ใช้งาน "'.$rs['username'].'"');
		$this->user->delete($id);
		set_notify('success', lang('delete_data_complete'));
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	function check_username()
	{
		$user = $this->db->getOne('select id from users where username = ? ',array($_GET['username']));	
		echo ($user)?"false":"true";
	}
	
	function test()
	{
		$this->db->debug = TRUE;
		$this->db->execute('delete from agency_details  
  
');
	}
}
?>